package com.orangelife.mobile.app.application;

import android.app.Activity;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.baidu.mapapi.SDKInitializer;
import com.common.jump.LocationJumper;
import com.common.sp.CommSp2;
import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.http.ILoginExpired;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.SystemInfoUtil;
import com.curry.orangelife.mobile.R;
import com.common.jump.CommonJumper;
import com.common.sp.SharedPreferUtil;
import com.datatrack.DataTrack;
import com.orangelife.arenasdk.main.Arena;
import com.orangelife.mobile.util.LogE;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.orangelife.mobile.common.db.DBHelper;
import com.thirdsdk.umeng.UMShare;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.umeng.analytics.MobclickAgent;
import com.zhuge.analysis.stat.ZhugeSDK;


import java.util.LinkedList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;


public class CurryApplication extends MultiDexApplication implements ILoginExpired {

    private static CurryApplication mInstance;

    private boolean isUpdate = true;

    private String time;

    private String walletID;

    /**
     * 判断是购物车还是立即购买
     */
    private boolean shopping;


    private Context mContext;
    private boolean isDebugHttp;
    private boolean isDebugSDK;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        mContext = getApplicationContext();
//        Intent intent = new Intent(this, InitAppService.class);
//        startService(intent);
        setDebug();
        initErrorHandlerV2();


        initHttpUtil();
        initStringUtil();
        initToastHelper();
        initSharePreferenceUtil();
//            setDebug();
        initZhuGe();
        initVolleyV3Helper();
        initImageLoader(getApplicationContext());
        initDBHelper();
                  /*第三方*/
        initUmengShare();// umeng分享
        SDKInitializer.initialize(getApplicationContext()); // 百度地图初始化
        JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志
        JPushInterface.init(getApplicationContext()); // 初始化 JPush
        SDKInitializer.initialize(getApplicationContext()); // 百度地图初始化

        initArena();
    }

    private void setDebug() {
        isDebugHttp = true;
        isDebugSDK = false;
        LogE.setDebug(false);
        HttpUtil.getHttp().setDebug(isDebugHttp);
        com.curry.android.http.OrangeErrorHandler.getInstance().setDebug(isDebugHttp);
        VolleyHttpUtil.getInstance().setDebug(isDebugHttp);
        VolleyHttpUtil.getInstance().setHeaderDebug(isDebugHttp);

    }

    public String getServerURL() {
        return getApplicationContext().getString(R.string.server_url);
    }

    public Context getContext() {
        return mContext;
    }

    private void initDBHelper() {
        DBHelper.init(getApplicationContext());
        DBHelper.getInstance();
    }

    private void initArena() {
        Arena.getInstance().initialize(getApplicationContext(), getServerURL());
    }

    /**
     * 旧版的HTTP Util
     */
    private void initHttpUtil() {
        HttpUtil.getHttp().setServerURL(getServerURL());
    }

    /**
     * 最新的Volley HTTP Util,V3
     */
    private void initVolleyV3Helper() {
        VolleyHttpUtil.getInstance().setServerURL(getServerURL());
        VolleyHttpUtil.getInstance().initVolleyHttpUtil(getApplicationContext());

    }

    /**
     * 设置小区ID到HTTP请求的头部
     */
    public void setCommID(Context context, boolean isNeedNewTask) {
        if (com.curry.android.util.StringUtil.isBlank(CommSp2.getCommID())) {
            LocationJumper.jumpToSelectCity(context, isNeedNewTask);
        } else {
            VolleyHttpUtil.getInstance().setHeader("commID", CommSp2.getCommID());
            HttpUtil.getHttp().setHeader("commID", CommSp2.getCommID());
        }
    }

    /**
     * 设置Token到Http请求的头部
     */
    public void setAccessToken() {
        VolleyHttpUtil.getInstance().setHeader("accessToken", UserSp.getAccessToken());
        VolleyHttpUtil.getInstance().setHeader("ver", SystemInfoUtil.getVersionName(getApplicationContext()));
        HttpUtil.getHttp().setHeader("accessToken", UserSp.getAccessToken());
        HttpUtil.getHttp().setHeader("ver", SystemInfoUtil.getVersionName(getApplicationContext()));
    }

    /**
     * 初始化诸葛IO
     */
    private void initZhuGe() {
//        ZhugeSDK.getInstance().openDebug();
//        ZhugeSDK.getInstance().openLog();
        /*参数openGestureBindingUI是可视化事件定义的开关，只有赋值为true时才能连接诸葛io进行
          事件定义。 打开此开关的设备，耗电会有所增加，但不影响应用的稳定。尽管如此，我们还是
          强烈建议您将打开此开关的 应用仅分发给需要的人员，正式分发给用户的版本，请将
          openGestureBindingUI设置为false.*/
        //ZhugeSDK.getInstance().codelessInit(this, isDebugSDK);
        DataTrack.initTrack(getApplicationContext(),DataTrack.ZHUGE);

    }

    /**
     * 初始化HTTP错误处理器，最新版
     */
    private void initErrorHandlerV2() {
        com.curry.android.http.OrangeErrorHandler.getInstance().initOrangeHttpBiz(getApplicationContext());
        com.curry.android.http.OrangeErrorHandler.getInstance().setLoginExpired(this);
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.shop_header) //
                .showImageForEmptyUri(R.drawable.shop_header)
                .showImageOnFail(R.drawable.shop_header)
                .cacheInMemory(true).cacheOnDisk(true).build();

        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.defaultDisplayImageOptions(defaultOptions);
        config.threadPriority(Thread.NORM_PRIORITY - 2);//default 设置当前线程的优先级
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB sd卡(本地)缓存的最大值
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        //config.writeDebugLogs(); // Remove for release app
        config.threadPoolSize(5);
        config.memoryCache(new WeakMemoryCache());
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    /**
     * umeng
     */
    private void initUmengShare() {
        UMShare.getInstance().init(getApplicationContext());
        MobclickAgent.setCatchUncaughtExceptions(true);
        /*集成测试时用，测试数据将不会被统计到正式后台*/
        //MobclickAgent.setDebugMode(true);
        //UmengUpdateAgent.update(this);
    }

    /**
     * 初始化StringUtil中的上下文
     *
     * @return
     */
    private void initStringUtil() {
        StringUtil.getInstance().init(getApplicationContext());
    }

    public static CurryApplication getInstance() {
        return mInstance;
    }

    private void initSharePreferenceUtil() {
        SharedPreferUtil.getInstance().initSharePrefs(getApplicationContext());
    }

    private void initToastHelper() {
        ToastHelper.getInstance().init(getApplicationContext());
        com.curry.android.util.ToastHelper.getInstance().init(getApplicationContext());
    }

    public boolean isUpdate() {
        return isUpdate;
    }

    public void setUpdate(boolean isUpdate) {
        this.isUpdate = isUpdate;
    }

    public void setValidity(String time) {
        this.time = time;
    }

    public String getValidity() {
        return time;
    }

    public void setWalletID(String walletID) {
        this.walletID = walletID;
    }

    public String getWalletID() {
        return walletID;
    }

    public void setShopping(boolean shopping) {
        this.shopping = shopping;
    }

    public boolean getShopping() {
        return shopping;
    }


    /*===================== 全部退出 start ========================*/

    /**
     * 打开的activity
     **/
    private List<Activity> activitiesList = new LinkedList<>();

    /**
     * 新建了一个activity
     *
     * @param activity   
     */
    public void addActivity(Activity activity) {
        activitiesList.add(activity);
    }

    /**
     * 结束指定的Activity
     *
     * @param activity 需要关闭的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            this.activitiesList.remove(activity);
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    public void finishLastActivity() {
        if (activitiesList != null && activitiesList.size() > 0) {
            Activity activity = activitiesList.get(activitiesList.size() - 2);
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    private void cancelAllHttpRequest() {
        VolleyHttpUtil.getInstance().cancelAll();
    }

    /**
     * 应用退出，结束所有未关闭的activity     
     */
    @Override
    public void exit() {
        int max = activitiesList.size() - 1;
        while (max >= 0) {
            if (activitiesList.get(max) != null) {
                activitiesList.get(max).finish();
            }
            max = max - 1;
        }
        activitiesList.clear();
        exitZhuge();
    }

    /**
     * 退出诸葛
     */
    private void exitZhuge() {
        ZhugeSDK.getInstance().flush(getApplicationContext());
    }

    @Override
    public void clearCache() {
    }

    @Override
    public void clearToken() {/*退出登录时用*/
        SharedPreferUtil.getInstance().clearLogin();/*全部清除*/
    }

    @Override
    public void jumpToLogin() {
        CommonJumper.jumpToLoginWhenExit(getApplicationContext());
    }

    /*========================== 全部退出 end =========================*/
}